package org.xs.object.utils;

import cn.hutool.json.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Repository;

@Repository
@PropertySource("classpath:TokenConfig.properties")
public class TokenUtil {
    private static String ENCRYPT_KEY;
    private static Long EXPIRE_TIME;
    private static String ISSUER;

    @Value("${token.issuer}")
    public void setIssuer(String issuer) {
        ISSUER = issuer;
    }

    @Value("${token.encrypt.key}")
    public void setEncryptKey(String encryptKey) {
        ENCRYPT_KEY = encryptKey;
    }

    @Value("${token.expire.time}")
    public void setExpireTime(String expireTime) {
        try {
            // 如果是表达式，可以使用脚本引擎计算
            if (expireTime.contains("*")) {
                // 简单的表达式计算处理
                String[] parts = expireTime.split("\\*");
                if (parts.length == 2) {
                    EXPIRE_TIME = Long.valueOf(parts[0].trim()) * Long.valueOf(parts[1].trim());
                } else {
                    EXPIRE_TIME = Long.valueOf(expireTime);
                }
            } else {
                EXPIRE_TIME = Long.valueOf(expireTime);
            }
        } catch (NumberFormatException e) {
            // 默认值
            EXPIRE_TIME = 300000L;
        }
    }

    public static String getToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            throw new RuntimeException(ResponseEnum.NO_TOKEN.getMag());
        }
        return token.substring(7);
    }

    //生成token
    public static String createToken(JSONObject jsonObject) {
        return JWT.create()
                .withSubject(jsonObject.toString())
                .withIssuer(ISSUER)
                .withExpiresAt(new java.util.Date(System.currentTimeMillis() + EXPIRE_TIME))
                .sign(Algorithm.HMAC256(ENCRYPT_KEY));
    }

    //验证token
    public static boolean verifyToken(String token) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(ENCRYPT_KEY)).withIssuer(ISSUER).build();
            jwtVerifier.verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String getDataFromToken(String token) {
        try {
            String data;
            String temp;
            temp = JWT.decode(token).getClaim("sub").asString();
            //userId= JWT.decode(actualToken).getClaim("Payload").asMap().get("sub");
            // 获取user_id
            //(userId.split(":"))[1] //因为{userId:5} 所以分割：
            //((userId.split(":"))[1]).split("}")[0];//因为结果 5}  所以分割id与}
            data = ((temp.split(":"))[1]).split("}")[0];
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}